<?php
/**
 * @author zhangrui
 */

namespace App\Common\RabbitMQ;

/**
 * MQ消费者
 * Class AbstractConsumer
 * @package App\Common\RabbitMQ
 */
class AbstractConsumer extends AbstractAMQP
{
    /** @var \AMQPQueue */
    protected $qu;
    /** @var string 队列名称 */
    protected $quName = 'test';
    /**
     * @var int 队列标志
     * 可选值：
     * AMQP_DURABLE
     * AMQP_PASSIVE
     * AMQP_EXCLUSIVE
     * AMQP_AUTODELETE
     */
    protected $quFlags = AMQP_DURABLE;
    /** @var array 队列参数 */
    protected $quArguments = [];
    /** @var null 绑定路由 */
    protected $quBindRoutingKey = null;
    /** @var array 绑定参数 */
    protected $quBindArguments = [];
    /** @var bool 主动声明队列 */
    protected $declareQu = false;

    /**
     * AbstractConsumer constructor.
     * @param bool $persistent 使用持久连接
     * @throws \AMQPChannelException
     * @throws \AMQPConnectionException
     * @throws \AMQPExchangeException
     * @throws \AMQPQueueException
     */
    public function __construct(bool $persistent = false)
    {
        parent::__construct($persistent);
        $this->qu = $this->newQueue($this->ch, $this->ex);
    }

    /**
     * @param \AMQPChannel $channel
     * @param \AMQPExchange $exchange
     * @return \AMQPQueue
     * @throws \AMQPChannelException
     * @throws \AMQPConnectionException
     * @throws \AMQPQueueException
     */
    protected function newQueue(\AMQPChannel $channel, \AMQPExchange $exchange)
    {
        $qu = new \AMQPQueue($channel);
        $qu->setName($this->quName);
        $qu->setFlags($this->quFlags);
        if ($this->quArguments) {
            $qu->setArguments($this->quArguments);
        }
        if ($this->declareQu) {
            $qu->declareQueue();
        }
        $qu->bind($exchange->getName(), $this->quBindRoutingKey, $this->quBindArguments);
        return $qu;
    }

    /**
     * @return \AMQPQueue
     */
    public function getQueue()
    {
        if (! $this->ch->isConnected() || ! $this->conn->isConnected()) {
            $this->qu = $this->newQueue($this->getChannel(), $this->getExchange());
        }
        return $this->qu;
    }
}
